package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"

	"github.com/gin-gonic/gin"
)

type HisDeptService struct {
	repo repository.HisDeptRepository
}

func NewHisDeptService(repo repository.HisDeptRepository) *HisDeptService {
	return &HisDeptService{repo: repo}
}

func (s *HisDeptService) CreateDept(c *gin.Context) {
	var dept model.HisDept
	if err := c.ShouldBindJSON(&dept); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Create(&dept); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, dept)
}

func (s *HisDeptService) GetDeptByID(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	dept, err := s.repo.GetByID(uint(idUint))
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, dept)
}

func (s *HisDeptService) UpdateDept(c *gin.Context) {
	var dept model.HisDept
	if err := c.ShouldBindJSON(&dept); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Update(&dept); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, dept)
}

func (s *HisDeptService) DeleteDept(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	if err := s.repo.Delete(uint(idUint)); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *HisDeptService) ListDeptsByHospital(c *gin.Context) {
	hospitalCode := c.Param("hospitalCode")
	depts, err := s.repo.ListByHospital(hospitalCode)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, depts)
}

func (s *HisDeptService) GetDeptByCode(c *gin.Context) {
	deptCode := c.Param("deptCode")
	dept, err := s.repo.GetByDeptCode(deptCode)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, dept)
}
